﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SlimDX;
using SKYPE4COMLib;
using Gype.UI;

namespace Gype.GUI.Components
{
    public class ConvList : Component
    {
        internal override void RenderObject()
        {
            mGUIManager.Target.PushClipArea(new System.Drawing.RectangleF(Location.X + 3, Location.Y + 5, Size.Width, Size.Height - 4));

            Vector2 curPos = new Vector2(Location.X + 30, Location.Y + 3);

            DateTime lastTimeStamp = DateTime.MaxValue;

            foreach (var chat in mChats)
            {
                if (chat.ActivityTimestamp.Date.CompareTo(lastTimeStamp.Date) != 0)
                {
                    curPos.Y += 8;
                    mGUIManager.Target.SetClipEnabled(false);
                    mGUIManager.Target.FillRectangle(new Vector2(0, curPos.Y - 2), new Vector2(Size.Width + 6, 19), BrushCollection.ConvListDateHeader);
                    mGUIManager.Target.SetClipEnabled(true);
                    string dateString = chat.ActivityTimestamp.ToString("dddd") + ", " + chat.ActivityTimestamp.ToShortDateString();

                    mChatText.Color = BrushCollection.ConvListDateText;
                    mChatText.DrawText(dateString, new Vector2(curPos.X - 27, curPos.Y), new Vector2(Size.Width - 12, 15));
                    curPos.Y += 23;
                    lastTimeStamp = chat.ActivityTimestamp;
                }

                string caption = UserManager.GetUserName(chat.DialogPartner);
                var user = UserManager.GetUser(chat.DialogPartner);

                mGUIManager.Target.DrawImage(ImageCollection.OnlineImageList[user.OnlineStatus], new System.Drawing.RectangleF(curPos.X - 23, curPos.Y, 16, 16));

                mChatText.Color = BrushCollection.ConvListConvText;
                mChatText.DrawText(caption, curPos, new Vector2(Size.Width - 36, 15));
                curPos.Y += 20;
            }

            mGUIManager.Target.PopClipArea();
        }

        public void AddChat(Chat cht)
        {
            mChats.Add(cht);
            mChats.Sort((c1, c2) =>
                {
                    return -c1.ActivityTimestamp.CompareTo(c2.ActivityTimestamp);
                }
            );
        }

        internal override void RenderTopLevel()
        {

        }

        internal override void AttachedToManager(Manager mgr)
        {
            base.AttachedToManager(mgr);
            mChatText = new TextElement(TextCollection.Arial);
            mChatText.Alignment = TextAlignement.Left;
            mChatText.Color = BrushCollection.ConvListDateText;
        }

        private List<Chat> mChats = new List<Chat>();
        private TextElement mChatText;
    }
}
